let express = require('express')
let app = express()
let http = require('http').createServer(app)
let io = require('socket.io')(http, {
    cors: {
        origin: '*'
    }
})

let clientList = {}

io.on('connection', (socket) => {
    console.log(1);
    let username = socket.handshake.query.username;
    if (!clientList[username]) clientList[username] = socket
    console.log(username + '上线了')
    socket.on('chat', (data) => {
        let {to,msg} = JSON.parse(data)
        if (clientList[to]) {
            clientList[to].emit('chat', JSON.stringify({
                from: username,
                msg
            }))
        } else {
            socket.emit('fail', '对方不在线')
        }
    })

    socket.on('disconnect', () => {
        delete clientList[username]
        console.log(username + '下线了')
    })
})

http.listen(3000, () => {
    console.log('listening on 3000');
})